package com.example.user.filter;

import com.example.user.domain.LoginUser;
import com.example.user.utils.SecurityUtils;
import com.example.user.utils.TokenWorker;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;

/**
 * token过滤器 验证token有效性
 */
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenWorker tokenWorker;

    //暂时处理
    private static final String[] SECURITY_IGNORE_API_PATH = {
            "/auth/login",
            "/swagger-ui.html",
            "/swagger-ui/**",
            "/v3/api-docs"
    };

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String requestURI = request.getRequestURI();
        return Arrays.stream(SECURITY_IGNORE_API_PATH)
                .anyMatch(pattern -> {
                    if (pattern.contains("**")) {
                        return requestURI.matches(pattern.replace("**", ".*"));
                    }
                    return requestURI.equals(pattern);
                });
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println(request.getHeader("Authorization"));
        LoginUser loginUser = tokenWorker.getLoginUser(request);
        if(loginUser != null && SecurityUtils.getAuthentication() == null) {
            // 如果认证过期，抛出CredentialsExpiredException
            if(loginUser.getExpireTime() < System.currentTimeMillis()) {
                throw new CredentialsExpiredException("用户认证有效期已过，请重新登录");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }


}
